package com.atguigu.jucdemo.test;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo02 {
    public static void main(String[] args) {
        SaleTicket2 saleTicket2 = new SaleTicket2();
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        try {
            for (int i = 1; i <= 50; i++) {
                executorService.execute(() -> {
                    saleTicket2.maipiao();
                });
            }
        } finally {
            executorService.shutdown();
        }
    }
}

class SaleTicket2 {
    private int num = 50;
    private Lock lock = new ReentrantLock();

    public void maipiao() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "取走了第" + (num--) + "张票,还剩余" + num + "张");
        } finally {
            lock.unlock();
        }
    }
}
